'use strict'

const { TaiSpider } = require('tai-spider');

const chronMap = [{
    dn: 'ID',
    fn: 'cospar'
}, {
    dn: 'Date',
    fn: 'launchDate',
}, {
    dn: 'Payload(s)',
    fn: 'satlist',
    type: 'array',
    options: {
        sep: '\n',
    }
}, {
    dn: 'Vehicle',
    fn: 'rocname',
}, {
    dn: 'Launch Vehicle',
    fn: 'rocname',
}, {
    dn: 'Site',
    fn: 'site',
}, {
    dn: 'Remark',
    fn: 'remark',
}]

class GunterChrSpider extends TaiSpider {

    constructor(options = {}) {
        super(options);
        this.name = 'gunter-chr';
        this.debug = true;
        this.start_urls = ['https://space.skyrocket.de/directories/chronology.htm'];
        // this.start_urls = ['https://space.skyrocket.de/doc_chr/lau2021.htm'];
    }

    *parse(response) {
        for (let ele of response.css('.index td')) {
            if (ele.css('a').get(0)) {
                yield response.follow(ele.css('a'), this.parseChr);
                // yield {
                //         link: ele.css('a').get(0).attr('href')
                //     }
            }
        }
    }

    * parseChr(response) {
        let chronlistEle = response.css('#chronlist').get(0);

        let chronlist = chronlistEle.parseTable({
            fieldNameMap: chronMap
        });

        for (let chron of chronlist) {
            if (chron.cospar === 'ID') continue;
            if (chron.satlist.length === 0) continue;

            // trans satlist from [string] to [object]
            chron.satlist = chron.satlist.map(sat => {
                return { name: sat }
            });
            
            yield {
                index_name: 'tai-gunter-launch',
                id: chron.cospar !== '-' ? chron.cospar : `plan-${chron.launchDate}`,
                ...chron,
            };
        }
    }

    * parseImage(response) {
        yield {
            index_name: 'tai-file',
            ...response.options.extData,
        }
    }
}

module.exports = GunterChrSpider;